//
//  VideoPlayerViewController.m
//  Frame
//
//  Created by 这是工作本 on 16/3/7.
//  Copyright © 2016年 这是工作本. All rights reserved.
//

#import "VideoPlayerViewController.h"

@interface VideoPlayerViewController ()

{
    BOOL _played; // 是否播放
    BOOL _isFullScreen; // 是否全屏
    BOOL _isTap; // 是否点击
    NSString *_totalTime; // 全部时间
    NSDateFormatter *_dateFormatter; // 关于时间设置
    
    NSInteger _count; // 判断播放到哪一首
}

@property (retain, nonatomic) AVPlayer *player; // 播放器
@property (retain, nonatomic) AVPlayerItem *playerItem;
@property (retain, nonatomic) PlayerView *playerView; // 视图容器

@property (retain, nonatomic) UIButton *stateB; // 播放按钮
@property (retain, nonatomic) UILabel *timeL; // 时间显示label

@property (retain, nonatomic) id playBackTimeObservier;
@property (retain, nonatomic) UISlider *videoSlider; // 滑条, 显示当前播放位置
@property (retain, nonatomic) UIProgressView *videoProgressV; // 进度条, 显示缓冲

@property (retain, nonatomic) UIView *hiddenV; // 视频下方显示条

@property (retain, nonatomic) UIButton *fullB; // 全屏按钮

@property (retain, nonatomic) NSMutableArray *myArr; // 视频数组

@property (nonatomic, assign) BOOL fullsceen;
@end

@implementation VideoPlayerViewController

// 单例创建播放器
+ (instancetype)sharePlayerViewConctroller {
    static VideoPlayerViewController *sharePlayerVC = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        sharePlayerVC = [[VideoPlayerViewController alloc]init];
        
    });
    
    return sharePlayerVC;

}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // 将各个bool值初始化
        _isFullScreen = NO;
        _played = NO;
        _isTap = YES;
        _count = 0;
        self.myArr = [NSMutableArray array];
        
    }
    return self;
}

- (void)viewDidDisappear:(BOOL)animated
{
    [self.playerView.player pause];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"视屏播放";
    self.view.backgroundColor = [UIColor whiteColor];
    
    //隐藏自动返回
    self.navigationItem.hidesBackButton = YES;
    
    //全屏隐藏导航栏
    self.fullsceen = YES;
    
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:29 / 255.0 green:127 / 255.0  blue:140 / 255.0  alpha:1.0];
    
    //返回按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"but_an.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonAction:)];
    
    //设置title颜色
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor colorWithRed:255 / 255.0 green:255 / 255.0 blue:255 / 255.0 alpha:1.0],NSForegroundColorAttributeName,nil]];
    
    [self createPlayer];



    
    
}


- (void)createPlayer
{
    self.myArr = [NSMutableArray arrayWithObjects:@"http://v.jxvdy.com/sendfile/w5bgP3A8JgiQQo5l0hvoNGE2H16WbN09X-ONHPq3P3C1BISgf7C-qVs6_c8oaw3zKScO78I--b0BGFBRxlpw13sf2e54QA", @"http://video.szzhangchu.com/sansemiantangB.mp4", @"http://video.szzhangchu.com/suansunzhuduhuoguoB.mp4",nil];
    
    NSURL *videoUrl = [NSURL URLWithString:[self.myArr objectAtIndex:_count]];
    
    
    self.playerView = [[PlayerView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    self.playerView.backgroundColor = [UIColor blackColor];
    
    [self.view addSubview:self.playerView];
    
    
    self.playerItem = [AVPlayerItem playerItemWithURL:videoUrl];
    // 监听status属性
    [self.playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
    // 监听loadedTimeRanges属性
    [self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    
    // 下方播放条
    self.hiddenV = [[UIView alloc] initWithFrame:CGRectMake(0, [[UIScreen mainScreen] bounds].size.height - 50 * ScreenHeigth, [[UIScreen mainScreen] bounds].size.width, 50 * ScreenHeigth)];
    self.hiddenV.alpha = 0.9;
    self.hiddenV.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.hiddenV];
    
    self.stateB = [UIButton buttonWithType:UIButtonTypeCustom];
    self.stateB.frame = CGRectMake(0, 0, 50 * ScreenWidth, 50 * ScreenHeigth);
    self.stateB.backgroundColor = [UIColor whiteColor];
    [self.stateB setTitle:@"播放" forState:UIControlStateNormal];
    [self.stateB setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [self.stateB addTarget:self action:@selector(stateButtonTouched:) forControlEvents:UIControlEventTouchUpInside];
    [self.hiddenV addSubview:self.stateB];
    
    self.videoSlider = [[UISlider alloc] initWithFrame:CGRectMake(50 * ScreenWidth, 0, [[UIScreen mainScreen] bounds].size.width  - 150 * ScreenWidth, 50 * ScreenHeigth)];
    self.videoSlider.tintColor = [UIColor blueColor];
    //self.videoSlider.backgroundColor = [UIColor whiteColor];
    
    [self.videoSlider addTarget:self action:@selector(videoSliderChangeValue:) forControlEvents:UIControlEventValueChanged];
    [self.videoSlider addTarget:self action:@selector(videoSlierChangeValueEnd:) forControlEvents:UIControlEventTouchUpInside];
    [self.hiddenV addSubview:self.videoSlider];
    
    self.videoProgressV = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 25 * ScreenHeigth, [[UIScreen mainScreen] bounds].size.width- 150 * ScreenWidth, 50 * ScreenHeigth)];
    self.videoProgressV.tintColor = [UIColor blueColor];
    
    [self.videoSlider addSubview:self.videoProgressV];
    
    self.timeL = [[UILabel alloc] initWithFrame:CGRectMake(self.videoSlider.frame.origin.x + self.videoSlider.frame.size.width, 0, 50 * ScreenWidth, 50 * ScreenHeigth)];
    self.timeL.textAlignment = NSTextAlignmentCenter;
    self.timeL.backgroundColor = [UIColor whiteColor];
    [self.hiddenV addSubview:self.timeL];
    
    
    
    
    self.playerView.player = _player;
    // 设置值	描述
    /*False	（缺省值）禁用（淡化）Button 所指定的按钮。这个按钮的功能在控件中是不可用的。
     True	启用 Button 所指定的按钮。这个按钮的功能在控件中是可用的。*/
    self.stateB.enabled = NO;
    
    
    self.fullB = [UIButton buttonWithType:UIButtonTypeCustom];
    self.fullB.frame = CGRectMake(self.timeL.frame.origin.x + self.timeL.frame.size.width, self.timeL.frame.origin.y, 50 * ScreenWidth, 50 * ScreenHeigth);
    self.fullB.backgroundColor = [UIColor yellowColor];
    
    [self.fullB addTarget:self action:@selector(fullScreen:) forControlEvents:UIControlEventTouchUpInside];
    [self.hiddenV addSubview:self.fullB];
    
    //self.hiddenV.hidden = YES;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.playerView addGestureRecognizer:tap];
    
    
    // 添加视频播放结束通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:_playerItem];
}
// 是否点击屏幕: 隐藏播放条
- (void)tapAction:(UITapGestureRecognizer *)tap {
    
    if (!_isTap) {
        
        _isTap = YES;
        self.hiddenV.hidden = NO;
        
    }
    else
    {
        _isTap = NO;
        self.hiddenV.hidden = YES;
    }
    
}

// 全屏设置方向和frame
- (void)fullScreen:(UIButton *)sender
{
    
    if (_isFullScreen) {
        _isFullScreen = NO;
        _isTap = NO;
        [UIView animateWithDuration:0.2 animations:^{
            
            self.playerView.transform = CGAffineTransformRotate(self.playerView.transform, -M_PI_2);
            
            self.playerView.frame = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height);
            
            CGAffineTransform rotation = CGAffineTransformMakeRotation(-1.57079633);
            
            self.hiddenV.transform = rotation;
            
            self.hiddenV.frame = CGRectMake(0, [[UIScreen mainScreen] bounds].size.height - 50 * ScreenHeigth, [[UIScreen mainScreen] bounds].size.width, 50 * ScreenHeigth);
            
            CGAffineTransform rotation1 = CGAffineTransformMakeRotation(1.57079633);
            
            self.stateB.transform = rotation1;
            self.stateB.frame = CGRectMake(0, 0, 50 * ScreenHeigth, 50 * ScreenHeigth);
            
            // y
            // x
            // h
            // w
            self.videoSlider.transform = rotation1;
            self.videoSlider.frame = CGRectMake(0, 50 * ScreenHeigth, 50 * ScreenWidth, [[UIScreen mainScreen] bounds].size.width - 150 * ScreenHeigth);
            //[self.hiddenV addSubview:self.videoSlider];
            
            self.timeL.transform = rotation1;
            self.timeL.frame = CGRectMake(0, [[UIScreen mainScreen] bounds].size.width - 100 * ScreenHeigth, 50 * ScreenWidth, 50 * ScreenHeigth);
            
            self.fullB.frame = CGRectMake(self.timeL.frame.origin.x, self.timeL.frame.origin.y + self.timeL.frame.size.width, 50 * ScreenWidth, 50 * ScreenHeigth);
            
            self.hiddenV.hidden = YES;
            
        }];
    }
    else
    {
        _isFullScreen = YES;
        _isTap = NO;
        [UIView animateWithDuration:0.2 animations:^{
            
            self.playerView.transform = CGAffineTransformRotate(self.playerView.transform, M_PI_2);
            
            self.playerView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
            
            CGAffineTransform rotation = CGAffineTransformMakeRotation(1.57079633);
            self.hiddenV.transform = rotation;
            self.hiddenV.frame = CGRectMake(0, 0, 50 * ScreenWidth, [[UIScreen mainScreen] bounds].size.height);
            
            CGAffineTransform rotation1 = CGAffineTransformMakeRotation(M_PI/2 * 4);
            self.stateB.transform = rotation1;
            self.stateB.frame = CGRectMake(0, 0, 50 * ScreenWidth, 50 * ScreenHeigth);
            
            self.videoProgressV.transform = rotation1;
            self.videoProgressV.frame = CGRectMake(0, 25 * ScreenWidth, [[UIScreen mainScreen] bounds].size.height - 150 * ScreenWidth, 50 * ScreenHeigth);
            
            self.videoSlider.transform = rotation1;
            self.videoSlider.frame = CGRectMake(50 * ScreenWidth, 0, [[UIScreen mainScreen] bounds].size.height - 150 * ScreenWidth, 50 * ScreenHeigth);
            //self.videoSlider.backgroundColor = [UIColor whiteColor];
            
            self.timeL.transform = rotation1;
            self.timeL.frame = CGRectMake(self.videoSlider.frame.origin.x + self.videoSlider.frame.size.width, 0, 50 * ScreenWidth, 50 * ScreenHeigth);
            
            self.fullB.frame = CGRectMake(self.timeL.frame.origin.x + self.timeL.frame.size.width, self.timeL.frame.origin.y, 50 * ScreenWidth, 50 * ScreenHeigth);
            self.fullB.backgroundColor = [UIColor yellowColor];
            
            self.hiddenV.hidden = YES;
        }];
        
    }
    
    if (YES == self.fullsceen) {
      
        //点击放大隐藏
        self.navigationController.navigationBarHidden = YES;
        self.fullsceen = NO;
        
    } else {
        
        self.navigationController.navigationBarHidden = NO;
        self.fullsceen = YES;
        
    }
    
    
    
    
    
}
// 播放时间
- (void)monitoringPlayback:(AVPlayerItem *)playerItem
{
    __block VideoPlayerViewController *VC = self;
    //__weak typeof(self) weakSelf = self;
    self.playBackTimeObservier = [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:NULL usingBlock:^(CMTime time) {
        
        
        CGFloat currentSecond = playerItem.currentTime.value/playerItem.currentTime.timescale;// 计算当前在第几秒
        [VC.videoSlider setValue:currentSecond animated:YES];
        
        //
        NSString *timeString = [VC convertTime:currentSecond];
        
        VC.timeL.font = [UIFont systemFontOfSize:10.0 * ScreenWidth];
        VC.timeL.text = [NSString stringWithFormat:@"%@/%@",timeString, _totalTime];
        
        NSLog(@"weakSelf.timeL.text %@", VC.timeL.text);
    }];
    
}

//KVO方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
    
    if ([keyPath isEqualToString:@"status"]) {
        
        if ([playerItem status] == AVPlayerStatusReadyToPlay) {
            
            
            NSLog(@"AVPlayerStatusReadyToPlay");
            
            self.stateB.enabled = YES;
            
            // 获取视频总长度
            CMTime duration = self.playerItem.duration;
            
            // 转换成秒
            CGFloat totalSecond = playerItem.duration.value / playerItem.duration.timescale;
            
            // 转换成播放时间
            _totalTime = [self convertTime:totalSecond];
            
            // 自定义UISlider外观
            [self customVideoSlider:duration];
            
            NSLog(@"movie total duration: %f", CMTimeGetSeconds(duration));
            
            // 监听播放状态
            [self monitoringPlayback:self.playerItem];
        }
        else if ([playerItem status] == AVPlayerStatusFailed)
        {
            NSLog(@"AVPlayerStatusFailed");
        }
    }
    else if ([keyPath isEqualToString:@"loadedTimeRanges"])
    {
        // 计算缓冲进度
        NSTimeInterval timeInterval = [self availableDuration];
        
        NSLog(@"Time Interval: %f", timeInterval);
        
        CMTime duration = _playerItem.duration;
        CGFloat totalDuration = CMTimeGetSeconds(duration);
        
        if (!_played) {
            [self.playerView.player pause];
            
        }
        else
        {
            
            [self.playerView.player play];
            
        }
        
        
        
        // 改变进度条进度
        [self.videoProgressV setProgress:timeInterval / totalDuration animated:YES];
        
        
    }
    
}
// 缓冲总时间
- (NSTimeInterval)availableDuration
{
    NSArray *loadedTimeRanges = [[self.playerView.player currentItem] loadedTimeRanges];
    
    // 获取缓冲区域
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];
    
    CGFloat startS = CMTimeGetSeconds(timeRange.start);
    CGFloat durationS = CMTimeGetSeconds(timeRange.duration);
    
    // 计算缓冲总进度
    NSTimeInterval result = startS + durationS;
    
    return result;
    
}
// 自定义UISlider外观
- (void)customVideoSlider:(CMTime)duration
{
    self.videoSlider.maximumValue = CMTimeGetSeconds(duration);
    
    UIGraphicsBeginImageContextWithOptions((CGSize){1, 1}, NO, 0.0f);
    
    UIImage *transparentImag = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    [self.videoSlider setMinimumTrackImage:transparentImag forState:UIControlStateNormal];
    [self.videoSlider setMaximumTrackImage:transparentImag forState:UIControlStateNormal];
    
}
// 播放按钮方法
- (void)stateButtonTouched:(UIButton *)sender
{
    if (!_played) {
        [self.playerView.player play];
        
        [self.stateB setTitle:@"停止" forState:UIControlStateNormal];
        
    }
    else
    {
        
        [self.playerView.player pause];
        
        [self.stateB setTitle:@"播放" forState:UIControlStateNormal];
    }
    _played = !_played;
}
// 改变slider值
- (void)videoSliderChangeValue:(id)sender
{
    UISlider *slider = (UISlider *)sender;
    
    
    NSLog(@"value change: %f", slider.value);
    
    if (0.000000 == slider.value) {
        
        __weak typeof(self) weakSelf = self;
        
        [self.playerView.player seekToTime:kCMTimeZero completionHandler:^(BOOL finished) {
            
            [weakSelf.playerView.player play];
            
        }];
        
    }
}
- (void)videoSlierChangeValueEnd:(id)sender
{
    
    UISlider *slider = (UISlider *)sender;
    
    NSLog(@"value end: %f", slider.value);
    
    CMTime changedTime = CMTimeMakeWithSeconds(slider.value, 1);
    
    __weak typeof(self) weakSelf = self;
    
    [self.playerView.player seekToTime:changedTime completionHandler:^(BOOL finished) {
        
        [weakSelf.playerView.player play];
        [weakSelf.stateB setTitle:@"停止" forState:UIControlStateNormal];
        
    }];
    
    
}

- (void)updateVideoSlider:(CGFloat)currentSecond
{
    [self.videoSlider setValue:currentSecond animated:YES];
}
// 播放结束
- (void)movePlayDidEnd:(NSNotification *)notification
{
    NSLog(@"Play end");
    
    if (self.myArr.count - 1 <= _count) {
        
        [self.playerView.player pause];
        
        [self.navigationController popViewControllerAnimated:YES];
    }
    else
    {
        _count++;
        [self createPlayer];
    }
}
// 播放时间显示
- (NSString *)convertTime:(CGFloat)second{
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:second];
    if (second/3600 >= 1) {
        
        //------------将字符串按formatter转成nsdate
        [[self dateFormatter] setDateFormat:@"HH:mm:ss"];
        
    } else
    {
        //------------将字符串按formatter转成nsdate
        [[self dateFormatter] setDateFormat:@"mm:ss"];
    }
    NSString *showtimeNew = [[self dateFormatter] stringFromDate:d];
    return showtimeNew;
}
- (NSDateFormatter *)dateFormatter
{
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
    }
    return _dateFormatter;
}



- (void)leftBarButtonAction:(UIBarButtonItem *)sender
{
    
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)dealloc {
    [self.playerItem removeObserver:self forKeyPath:@"status" context:nil];
    [self.playerItem removeObserver:self forKeyPath:@"loadedTimeRanges" context:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:self.playerItem];
    [self.playerView.player removeTimeObserver:self.playBackTimeObservier];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
